package com.example.server.web.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.server.web.config.SysConfig;
import com.example.server.web.domain.RespBean;
import com.example.server.web.domain.SysUser;
import com.example.server.web.domain.page.PageQueryDto;
import com.example.server.web.domain.dto.SysUserDto;
import com.example.server.web.domain.dto.UserLoginParam;
import com.example.server.web.domain.vo.SysUserVo;
import com.example.server.web.service.SysUserService;
import com.example.server.web.service.UserRoleService;
import com.example.server.web.utils.LoginUserUtil;
import com.example.server.web.utils.file.FileUploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  用户前端控制器
 * </p>
 *
 * @author 作者
 * @since 2023-04-04
 */
@RestController
@RequestMapping("/sys-user")
@Api(tags = {"用户接口"})
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private UserRoleService userRoleService;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public RespBean login(@Validated @RequestBody UserLoginParam userLoginParam){
       return sysUserService.login(userLoginParam);
    }

    /**
     * 注销
     * */
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        //清空登录用户的认证
        return RespBean.success("注销成功！");
    }

    @ApiOperation("分页获取用户列表")
    @PostMapping("/list")
    public RespBean getUsersPage(@Validated @RequestBody PageQueryDto pageQueryDto){
        Map map = sysUserService.getUsersPage(pageQueryDto);
        return RespBean.success("查询成功",map);
    }
    @ApiOperation("根据角色获取用户列表")
    @PostMapping("/list-role")
    public RespBean getUsersByRole(@Validated @RequestBody PageQueryDto pageQueryDto){
        Page<SysUser> page = sysUserService.getUsersByRole(pageQueryDto);
        HashMap<String,Object> ans = new HashMap<>();
        ans.put("sysUsersList",page.getRecords());
        ans.put("total",page.getTotal());
        return RespBean.success("查询成功",ans);
    }

    @ApiOperation("根据id获取用户信息(包含角色信息)")
    @GetMapping("/select/{userId}")
    public RespBean getsUserById(@PathVariable("userId") Long userId){
        SysUser sysUser = sysUserService.getUserById(userId);
        //新建dto对象
        SysUserVo userVo = new SysUserVo();
        BeanUtils.copyProperties(sysUser,userVo);
        userVo.setRoles(userRoleService.getRolesByUserId(userId));
        return RespBean.success("查询成功",userVo);
    }

    @ApiOperation("增加用户")
    @PostMapping("/add")
    public RespBean insertSysUser(@Validated @RequestBody SysUserDto sysUserDto) throws IOException {

        Integer ans = sysUserService.insertUser(sysUserDto);

        if (ans!=1){
            return RespBean.error(401,"增加失败",null);
        }
        return RespBean.success("增加成功",ans);
    }

    @ApiOperation("更新用户信息")
    @PutMapping("/update")
    public RespBean updatesysUser(@RequestBody SysUserDto sysUserDto){
        Integer ans = sysUserService.updateUser(sysUserDto,true);
        return RespBean.success("更新成功",ans);
    }

    @ApiOperation("删除用户信息")
    @DeleteMapping ("/delete/{sysUserId}")
    public RespBean deleteUser(@PathVariable("sysUserId") Long sysUserId){
        Integer ans = sysUserService.deleteUser(sysUserId);
        return RespBean.success("删除成功",ans);
    }

    @ApiOperation("批量删除用户信息")
    @DeleteMapping ("/deletes")
    public RespBean deleteysUser(@RequestBody List<Long> sysUserIdList){
        Integer ans = sysUserService.deleteUsers(sysUserIdList);
        return RespBean.success("删除成功",ans);
    }

    @ApiOperation("上传头像")
    @PostMapping ("/uploadPhoto")
    public RespBean uploadPhoto(@RequestPart MultipartFile file) throws IOException {
        // 上传文件路径
        String filePath = SysConfig.getProfile();
        // 上传并返回新文件存储相对路径
        String fileName = FileUploadUtils.upload(filePath, file,SysConfig.IMAGE_EXTENSION);
        return RespBean.success("上传成功",fileName);
    }


    @ApiOperation("修改用户头像（登录用户）")
    @PostMapping ("/updatePhoto")
    public RespBean updatePhoto(@RequestPart MultipartFile file) throws IOException {
        // 上传文件路径
        String filePath = SysConfig.getProfile();
        // 上传并返回新文件存储相对路径
        String fileName = FileUploadUtils.upload(filePath, file,SysConfig.IMAGE_EXTENSION);
        Long id = LoginUserUtil.getLoginUser().getId();
        sysUserService.uploadPhoto(id,fileName);
        return RespBean.success("修改成功",fileName);
    }

    @ApiOperation("初始化密码")
    @GetMapping("/initPassword/{id}")
    public RespBean initPassword(@PathVariable("id") Long id) throws IOException {
        if (sysUserService.initPassword(id)){
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");

    }

}
